package com.tros.customer.features;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class WithinTransfer
 */
@WebServlet("/WithinTransfer")
public class WithinTransfer extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public WithinTransfer() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		Connection connect =null;			 
		HttpSession ses = request.getSession();
		
		String accType = request.getParameter("accType");
		String accNo = request.getParameter("accno");
		String balance = request.getParameter("balAmt");
		String transAmt = request.getParameter("tranAmt");
		String transName = request.getParameter("tranAmt");
		String tranaccNo = request.getParameter("tranaccNo");
		String tranacctype = request.getParameter("rety");
		
		System.out.println("accType :"+accType);
		System.out.println("balance :"+balance);
		System.out.println("transAmt :"+transAmt);
		System.out.println("transName :"+transName);
		System.out.println("tranaccNo :"+tranaccNo);
		System.out.println("accNo :"+accNo);
		
		try{
			  System.out.println("--------------> balance -------> "+Long.parseLong(balance));
			  System.out.println("--------------> transAmt -------> "+Long.parseLong(transAmt)); 
			  
	           if(Double.parseDouble(balance) < Double.parseDouble(transAmt))
	           {
	        	   ses.setAttribute("transferResult", "Transfer Amount Entered Exceeds Account Balance");
			       response.sendRedirect("passTransfer.jsp");
	           }else
	           {
	        	   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
			       connect =DriverManager.getConnection("jdbc:odbc:bank","root", " ");
		           System.out.println("DB Connection created :"+connect);
		           
	        	   Double bal = Double.parseDouble(balance)-Double.parseDouble(transAmt);
		           System.out.println("----------> amount ---------->"+bal);
		           
		           boolean find = findAcc(connect,tranaccNo,tranacctype);
		           
		           if(find != false)
		           {
		        	   DetectAcc(connect,accType,accNo,bal,ses);
		        	   try{
							
							 UpdateTrans trans = new UpdateTrans(connect,accNo,accType,"Fund Transfer",transAmt,String.valueOf(ses.getAttribute("currentID")));
							 trans.updateTransValues();
							 
							 						 
						}catch(Exception e)
						{
							e.printStackTrace();
							System.out.println(" -----------> Failed in updation trans --------");
						}
		        	   ses.setAttribute("transferResult", "Amount Successfully Transferred to Receipient Account");
				       response.sendRedirect("passTransfer.jsp");
		           }else
		           {
		        	   ses.setAttribute("transferResult", "Recepitent Account Number doesnt Match Bank Records");
				       response.sendRedirect("passTransfer.jsp");
		           }
	           }
	           
		}catch(Exception e)
		{
			ses.setAttribute("transferResult", "Amount Transfer Failure \n Please Try again");
	        response.sendRedirect("passTransfer.jsp");
			System.out.println("Failed here --------->"+e.getMessage());
	       	e.printStackTrace();
		}
		
	}
	
	private boolean findAcc(Connection connect, String tranaccNo,
			String tranacctype) {
		// TODO Auto-generated method stub
		try
		{
			PreparedStatement state;
			if(tranacctype.equals("Savings"))
			{
				state=connect.prepareStatement("SELECT * FROM SAVACC WHERE SAVACCNO=?");
			}else
			{
				state=connect.prepareStatement("SELECT * FROM CHCKACC WHERE CHCKACCNO=?");
			}		
			
			state.setString(1,tranaccNo);
			
            ResultSet result=state.executeQuery();
			
			if(result.next()){
				state.close();
				result.close();
				return true;
			}else{
				state.close();
				result.close();
				return false;
			}			
			
		}catch(Exception e)
		{
               System.out.println(" value return"+e.getMessage());
		}
		
		return false;
	}

	private void DetectAcc(Connection connect, String accType, String accNo,
			Double bal, HttpSession ses) {
		// TODO Auto-generated method stub
		
		try{
			PreparedStatement state;
			
			  if(accType.equals("Savings")){				  
				  state=connect.prepareStatement( "UPDATE SAVACC SET ACC_BALANCE=? WHERE "+"CUSTOMERID="+ses.getAttribute("currentID"));            
			  }else
			  {				  
				   state=connect.prepareStatement( "UPDATE CHCKACC SET ACC_BALANCE=? WHERE "+"CUSTOMERID="+ses.getAttribute("currentID"));	           
			  }
			  
			state.setString(1,String.valueOf(bal));
	   	    state.executeUpdate();
	   	    state.close();
	  		System.out.println("---------> connect value ------"+connect);
			
		}catch(Exception e)
		{
			System.out.println("Failed here update amount --------->");
			e.printStackTrace();
		}
		
	}

}
